package com.xudow.app.dynamicstate_old.module;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.jude.utils.JUtils;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.entity.UMessage;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.dynamicstate_old.data.RongYunModel;
import com.xudow.app.dynamicstate_old.domain.Config;
import com.xudow.app.dynamicstate_old.domain.MessageEvent;
import com.xudow.app.dynamicstate_old.module.discovery.DiscoverFragment;
import com.xudow.app.dynamicstate_old.module.discovery.search.SearchActivity;
import com.xudow.app.dynamicstate_old.module.follow.FollowFragment;
import com.xudow.app.dynamicstate_old.module.follow.NewDynamicActivity;
import com.xudow.app.dynamicstate_old.module.recommend.RecommendFragment;
import com.xudow.app.newui.PreLoginActivity;
import com.xudow.app.newui.base.BaseUiFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscription;
import rx.functions.Action1;

public class DynamicStateFragment extends BaseUiFragment {

    @BindView(R.id.dynamic_topbar_msg)
    ImageView dynamicTopbarMsg;
    @BindView(R.id.dynamic_write)
    ImageView dynamicWrite;
    @BindView(R.id.dynamic_tablayout)
    TabLayout mTabLayout;
    @BindView(R.id.dynamic_viewpager)
    ViewPager mViewPager;

    private static final String FOLLOWS = "关注";
    private static final String EXPLORER = "发现";
    private static final String RECOMMEND = "推荐";

    public static final String EVENT_GO_TO_DISCOVER = "goToDiscover";
    @BindView(R.id.title_search_iv)
    RelativeLayout titleSearchIv;

    /**
     * 新建“动态”
     *
     * @param view
     */
    @OnClick(R.id.dynamic_write)
    public void writeNewDynamic(View view) {
        XApplication application = (XApplication) getActivity().getApplication();
        if (!application.isLogin()) {
            startActivity(new Intent(getActivity(), PreLoginActivity.class));
        } else {
            Intent intent = new Intent(getActivity(), NewDynamicActivity.class);
            startActivityForResult(intent, Config.Code_NeedRefresh);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dynamic_state, container, false);
        ButterKnife.bind(this, view);
//        Log.e("profileId", getApp().getUserProfileId() + "");
//        Log.e("tokenRongcloud", getApp().getTokenRongcloud() + "");
//        Log.e("hasAttentionType", getApp().isHasAttentionType() + "");
        return view;
    }

    Subscription subscription;

    @Override
    protected void initData() {
        initViews();
//        getActivity().findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                startActivity(new Intent(getActivity(), MainActivity.class));
//            }
//        });
        subscription = RongYunModel.getInstance().registerNotifyCount(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                if (integer > 0) {
                    dynamicTopbarMsg.setImageResource(R.drawable.dynamic_message_new);
                } else {
                    dynamicTopbarMsg.setImageResource(R.drawable.dynamic_message);
                }
            }
        });
        registerUmengMessage();
    }

    private void registerUmengMessage() {
        PushAgent.getInstance(getActivity()).setMessageHandler(new UmengMessageHandler() {
            @Override
            public void dealWithNotificationMessage(Context context, UMessage uMessage) {
                dynamicTopbarMsg.setImageResource(R.drawable.dynamic_message_new);
                super.dealWithNotificationMessage(context, uMessage);
            }

            @Override
            public void dealWithCustomMessage(Context context, UMessage uMessage) {
                super.dealWithCustomMessage(context, uMessage);
            }
        });
    }

    @Subscribe
    public void onGodtoDiscover(MessageEvent event) {
        if (event.message.equals(EVENT_GO_TO_DISCOVER)) {
            mViewPager.setCurrentItem(1);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }


    private void initViews() {
        titleSearchIv.setOnClickListener(v -> {
            startActivity(new Intent(getContext(), SearchActivity.class));
        });
        dynamicTopbarMsg.setOnClickListener(v -> {
            dynamicTopbarMsg.setImageResource(R.drawable.dynamic_message);
            if (XApplication.getInstance().isLogin())
                RongYunModel.getInstance().chatList(getContext());
            else
                startActivity(new Intent(getContext(), PreLoginActivity.class));
        });
        FragmentPagerAdapter adapter = new PagerAdapter(getChildFragmentManager());
        mViewPager.setAdapter(adapter);
        mTabLayout.setTabTextColors(Color.GRAY, Color.parseColor("#55c11f"));
        mTabLayout.setSelectedTabIndicatorColor(Color.parseColor("#55c11f"));
        mTabLayout.setupWithViewPager(mViewPager);
    }

    @Override
    protected void initListener() {

    }

    private class PagerAdapter extends FragmentPagerAdapter {

        private static final int FOLLOW_POS = 0;
        private static final int EXPLORER_POS = 1;
        private static final int RECOMMEND_POS = 2;

        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case FOLLOW_POS:
                    return new FollowFragment();
                case EXPLORER_POS:
                    return new DiscoverFragment();
                case RECOMMEND_POS:
                    return new RecommendFragment();
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case FOLLOW_POS:
                    return FOLLOWS;
                case EXPLORER_POS:
                    return EXPLORER;
                case RECOMMEND_POS:
                    return RECOMMEND;
                default:
                    return null;
            }
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        for (Fragment fragment : getChildFragmentManager().getFragments()) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (subscription != null) {
            subscription.unsubscribe();
        }
    }
}
